﻿using CoreShop.App;
using CoreShop.Model;
using Microsoft.AspNetCore.SignalR.Client;
using Newtonsoft.Json;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;



namespace CoreShop.App
{
    public static class SignaRlHelp
    {
        public static HubConnection connection;
        public static HubConnection GetConnection(string name)
        {
            try
            {
                string channel = string.Format(":{0}/chat", AppConstVars.sysStore.channel);
                string url = AppConstVars.systemsetup.corehubUrl + channel;
                connection = new HubConnectionBuilder().WithUrl(url).WithAutomaticReconnect(new RetryPolicy()).Build();
                //connection = new HubConnectionBuilder().WithUrl(url).WithAutomaticReconnect().Build();
                //重连成功
                connection.Reconnected += async (string error) =>
                {
                    SignalRUser user = new SignalRUser();
                    user.connectionId = connection.ConnectionId;
                    user.storeId = AppConstVars.sysUser.storeId.ToString();
                    ClientMessage message = new ClientMessage();
                    message.type = "userInfo";
                    message.content = JsonConvert.SerializeObject(user);
                    //连接成功后通知服务端写入用户信息
                    await connection.InvokeAsync<string>("CallByClient", $"{JsonConvert.SerializeObject(message)}");
                };
                //断线重连
                connection.Closed += async (Exception error) =>
                {
                    //await Task.Delay(new Random().Next(0, 5) * 1000);
                    //await connection.StartAsync();
                };
                //被服务器端调用
                //connection.On<string>("CallByServer", (string str) =>
                //{
                //    global::System.Console.WriteLine($"{name} : {connection.ConnectionId} 收到消息:{str}");
                //});
            }
            catch (Exception error) {
                //SysClass.WriteTxtLog(error.Message);
            }
            return connection;
        } 
    }

    //实现IRetryPolicy接口
    class RetryPolicy : IRetryPolicy
    {
        /// <summary>
        /// 重连规则：重连次数<50：间隔1s;重试次数<250:间隔30s;重试次数>250:间隔1m
        /// </summary>
        /// <param name="retryContext"></param>
        /// <returns></returns>
        public TimeSpan? NextRetryDelay(RetryContext retryContext)
        {
            var count = retryContext.PreviousRetryCount / 50;
            if (count < 1)//重试次数<50,间隔1s
            {
                return new TimeSpan(0, 0, 1);
            }
            else if (count < 5)//重试次数<250:间隔30s
            {
                return new TimeSpan(0, 0, 30);
            }
            else //重试次数>250:间隔1m
            {
                return new TimeSpan(0, 1, 0);
            }
        }
    }
}
